package com.dcm.seckill.mq;

import com.dcm.seckill.mapper.SeckillOrderMapper;
import com.dcm.seckill.mapper.SeckillShopMapper;
import com.dcm.seckill.entity.SeckilOrderEntity;
import com.dcm.seckill.service.SeckillShopService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 牛浩
 */
@Component
public class SeckillConsumer {
    @Autowired
    private SeckillShopService seckillShopService;
    @Autowired(required = false)
    private SeckillShopMapper seckillShopMapper;
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @RabbitListener(queues = "seckillQ")
    public void consume(String msg){
        //获取用户信息
        String userName=msg.split("/")[0];
        //获取商品信息
        String id=msg.split("/")[1];
        //更新缓存数据
        Long decr = redisTemplate.opsForValue().increment(id, -1);
        if (decr<0){
            //if进入,说明商品已经被其他的消费端秒杀完了
            System.out.println("商品已经秒杀完了");
            return;
        }
        //减库存
        seckillShopMapper.reduce(Long.parseLong(id),Integer.valueOf(String.valueOf(decr)));
        System.out.println("用户:"+userName+"秒杀成功");
        //成功减库存,用户秒杀也就成功 添加订单
        SeckilOrderEntity order = new SeckilOrderEntity();
        order.setUserName(userName);
        order.setState(0);
        order.setShopId(Integer.valueOf(id));
        order.setCreateDate(new Date());
        seckillOrderMapper.insert(order);
    }
}
